<template>
	<div class="w-100%">
		<el-cascader
			v-if="detail === false"
			ref="cascader"
			:options="options"
			:show-all-levels="false"
			filterable
			clearable
			collapse-tags
			collapse-tags-tooltip
			@change="cascaderChange"
			v-bind="$attrs"
		>
			<template v-for="(slotKey, slotIndex) in Object.keys($slots)" :key="slotIndex" v-slot:[slotKey]>
				<slot :name="slotKey"></slot>
			</template>
		</el-cascader>
		<template v-else>
			{{
				selectDictLabel(treeRevert(options, $attrs.props.value), $attrs.modelValue, ',', {
					dictValue: $attrs.props.value,
					dictLabel: $attrs.props.label
				})
			}}
		</template>
	</div>
</template>

<script setup name="MyCascader">
import { API_HOST } from '@/config';
import axios from '@u/axios';
import _camelCase from 'lodash/camelCase';

const emits = defineEmits(['getLabel']),
	attrs = useAttrs(),
	/***
	 * 参数属性
	 * @property {list[]} list 数据源
	 * @property {String} type store.dispatch的方法名,兼容'GETdeptTree'/'deptTree'/'dept_tree'三种方式
	 * @property {String，Function} api 数据请求地址，默认请求为·GET·方式，支持传递url地址、api请求方法两种
	 * @property {Boolean} detail 是否为详情展示形式，默认为false
	 */
	props = defineProps({
		type: {
			type: String
		},
		list: {
			type: Array,
			default: () => []
		},
		api: {
			type: [String, Function],
			default: ''
		},
		detail: {
			type: Boolean,
			default: false
		}
	}),
	cascader = shallowRef(null);

const dictType = computed(() => (props.type ? (props.type?.startsWith?.('GET') ? props.type : `GET${_camelCase(props.type)}`) : '')),
	options = ref([]);

watch(
	() => props.list,
	(val) => {
		options.value = val || [];
	},
	{ deep: true, immediate: true }
);

watch(
	() => props.api,
	(val) => {
		if (val) {
			if (typeof val === 'string') {
				axios({
					method: 'get',
					url: API_HOST + val
				}).then((res) => {
					options.value = res.data || [];
				});
			}
			if (typeof val === 'function') {
				val().then((res) => {
					options.value = res.data || [];
				});
			}
		}
	},
	{ immediate: true }
);

watch(
	() => $store?.com[unref(dictType)?.replace('GET', '')],
	(val) => {
		if (unref(dictType)) options.value = val;
	},
	{ deep: true, immediate: true }
);

/**
 * 初始化执行逻辑
 */
if (unref(dictType)) {
	const dictTypeFn = $store?.com[unref(dictType)];
	if (isFunction(dictTypeFn)) {
		dictTypeFn();
	} else {
		throw new Error('type 全局数据传入，但无对应执行方法！');
	}
}

function cascaderChange() {
	if (!attrs.props.multiple) {
		emits('getLabel', unref(cascader).getCheckedNodes()[0]?.label || '');
		unref(cascader).togglePopperVisible(false);
	} else {
		emits('getLabel', unref(cascader).getCheckedNodes() || []);
	}
}
</script>
